package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/ctx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Order 订单
type Order struct {
}

// ListHandler 列表
func (o *Order) ListHandler(c *gin.Context) {
	var data []model.Order
	if err := orm.DbFind(&data); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(data, c)
}

// PageHandler 分页
func (o *Order) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.Order
	total, _ := p.DbModelWhere(&model.Order{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// GetHandler 查询
func (o *Order) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Order{}, c)
}

// DeliverHandler 发货
func (o *Order) DeliverHandler(c *gin.Context) {
	idstr := c.Param("id")
	if idstr == "" {
		ctx.JSONWriteError(nil, c)
		return
	}
	ids := util.StringSplit(idstr, ",")
	if err := orm.DbUpdateByID(&model.Order{}, ids, orm.H{"Status": 2}); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 关闭
func (o *Order) CloseHandler(c *gin.Context) {
	idstr := c.Param("id")
	if idstr == "" {
		ctx.JSONWriteError(nil, c)
		return
	}
	ids := util.StringSplit(idstr, ",")
	if err := orm.DbUpdateByID(model.Order{}, ids, orm.H{"Status": 4}); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// AddHandler 新增
func (o *Order) AddHandler(c *gin.Context) {
	var p model.Order
	//获取参数
	if err := c.ShouldBind(&p.OrderOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *Order) UpdateHandler(c *gin.Context) {
	var p model.Order
	//获取参数
	if err := c.ShouldBind(&p.OrderOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *Order) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Order{}, c)
}

func (o Order) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
}
